package com.jdjr.drools.demo;

import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.definition.KnowledgePackage;
import org.kie.internal.io.ResourceFactory;

import java.util.Collection;

public class RuleRunner {

    public void runRules(String[] rules, Object[] facts) {

        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

        for (int i = 0; i < rules.length; i++) {
            String ruleFile = rules[i];
            System.out.println("Loading file: " + ruleFile);
            kbuilder.add(ResourceFactory.newClassPathResource(ruleFile, RuleRunner.class), ResourceType.DRL);
        }

        Collection<KnowledgePackage> knowledgePackages = kbuilder.getKnowledgePackages();
        kbase.addKnowledgePackages(knowledgePackages);
        KieSession ksession = kbase.newKieSession();

        for (int i = 0; i < facts.length; i++) {
            Object fact = facts[i];
            System.out.println("Inserting fact: " + fact);
            ksession.insert(fact);
        }

        int i = ksession.fireAllRules();

        System.out.println(i);
    }
}
